package com.ziyia.a8_4_1.myview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

public class TouchZoomImageView extends View {

    private static final String TAG = "--------";
    private GestureDetector detector;

    private Bitmap bitmap;
    private Matrix matrix = new Matrix();

    private float prevDist;
    private float totalScaleRadio = 1.0f;
    private float totalTranslateX = 0.0f;
    private float totalTranslateY = 0.0f;

    public TouchZoomImageView(Context context, AttributeSet set) {
        super(context, set);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // 只处理触碰点大于或等于2（必须是多点触碰）的情形
        if (event.getPointerCount() >= 2) {
            // 对于多点触碰事件，需要使用 getActionMasked 来获取事件类型
            switch(event.getActionMasked()) {
                // 处理手指按下的事件
                case MotionEvent.ACTION_POINTER_DOWN:
                    // 计算两个手指之间的距离
                    prevDist = calSpace(event);
                    break;
                // 处理手指移动的事件
                case MotionEvent.ACTION_MOVE:
                    float curDist = calSpace(event);
                    float scaleRatio = curDist / prevDist;
                    totalScaleRadio *= scaleRatio;
                    postInvalidate();
                    prevDist = curDist;
                    break;
            }
        }
        return true;
    }


    // 计算两个手指之间的距离
    private float calSpace(MotionEvent event) {
        // 两点之间的距离 = 前一个位置 - 后一个位置
        float x = event.getX(0) - event.getX(1);
        // 两点之间的距离 = 前一个位置 - 后一个位置
        float y = event.getY(0) - event.getY(1);
        float sqrt = (float) Math.sqrt(x * x + y * y);
        Log.d(TAG, "calSpace() called with: sqrt = [" + sqrt + "]");
        return sqrt;
    }
}
